import json
import functools
from Spider.settings import PROXY_ENABLED
from Spider.Exception.exceptions import SetterError


def add_proxy(func):
    @functools.wraps(func)
    def inner(self, objs, *args, **kwargs):
        for obj in objs:
            if obj.need_proxy:
                proxy = self.get_proxy()
                if proxy is None:
                    break
                if isinstance(proxy, bytes):
                    proxy = proxy.decode('utf-8')
                obj.proxy = proxy
        func(self, objs, *args, **kwargs)
    return inner


def handle_deal(deal_list):
    lis = []
    for dic in deal_list:
        one_deal_list = []
        for key, value in dic.items():
            one_deal_list.append(key + ':' + str(value))
        one_deal_str = '   '.join(one_deal_list)
        lis.append(one_deal_str)
    for index, item in enumerate(lis):
        lis[index] = item.replace('title', f'优惠{index+1}')
    full_str = ';'.join(lis)
    full_str = full_str.replace('price', '价格').replace('soldCounts', '售出数量')
    return full_str


class HttpRequest(object):
    def __init__(self, url, meta, callback, cookies=None,headers=None, proxy=None,
                 need_proxy=PROXY_ENABLED, timeout=10, fail_time=0):
        self.url = url
        self.meta = meta
        self.cookies = cookies
        self.headers = headers
        self.proxy = proxy
        self.callback = callback
        self.need_proxy = need_proxy
        self.timeout = timeout
        self.fail_time = fail_time

    def __setitem__(self, key, value):
        self.__dict__[key] = value


class HttpResponse(object):
    def __init__(self, status, text_data, callback, meta):
        self.status = status
        self.text_data = text_data
        self.callback = callback
        self.meta = meta
    
    @property
    def text(self):
        return self.text_data

    @text.setter
    def text(self, data):
        raise SetterError("The text attribute can't setter")

    def json(self):
        if isinstance(self.text_data, str):
            try:
                return json.loads(self.text_data)
            except:
                return None
        if isinstance(self.text_data, bytes):
            return json.loads(self.text_data.decode('utf-8'))

    
class Item(dict):
    pass


if __name__ == '__main__':
    # dic = [
    #     {'title': '100元午餐代金卷1张，可叠加', 'price': 68, 'soldCounts': 59},
    #     {'title': '超值双人餐，提供免费WiFi', 'price': 79, 'soldCounts': 279},
    #     {'title': '新品六人餐，提供免费WiFi', 'price': 338, 'soldCounts': 7},
    #     {'title': '新品四人餐，提供免费WiFi', 'price': 179, 'soldCounts': 40},
    #     {'title': '100元代金卷1张，可叠加', 'price': 85, 'soldCounts': 3371}
    # ]   # title:title-value title:title-value;title:title-value title:title-value
    # a = handle_deal(dic)
    # print(a)
    # deal_list = a.split(';')
    # for item in deal_list:
    #     print(item)

    a = HttpRequest('www', 1)
    print(a.headers)
    print(a.need_proxy)

